<?php

namespace App\Http\Controllers\Root;

use App\Tag;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\TagRequest;

class TagController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->data['title'] = '标签列表';
        $this->data['datas'] = Tag::paginate(5);
        return view('root.tags.index', $this->data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->data['title'] = '新增标签';
        return view('root.tags.create', $this->data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(TagRequest $request)
    {
        $data = [
            'name' => $request->get('name'),
            'user_id' => \Auth::id()
        ];
        if (Tag::create($data)) {
            return $this->_success(route('root.tags.index'));
        }
        return $this->_error();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return redirect()->route('root.tags.edit',[$id]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->data['title'] = '编辑标签';
        $this->data['the_data'] = Tag::findOrFail($id);
        return view('root.tags.edit', $this->data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(TagRequest $request, $id)
    {
        $the_data = Tag::findOrFail($id);
        $the_data->name = $request->get('name');
        if ($the_data->save()) {
            return $this->_success();
        }
        return $this->_error();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $the_data = Tag::findOrFail($id);
        if ($the_data->delete()) {
            return $this->_success('#');    // #用来刷新当前页面
        }
        return $this->_error();
    }
}
